package com.jackyzgy.test.code;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 3DES加密解密
 * 
 * @author yedecan
 * @version 1.7
 */
public class Des3Encrypt {
	private static final Log log = LogFactory.getLog(Des3Encrypt.class);
	
    private static final String CRYPT_ALGORITHM = "DESede";
    
	private String key = "4ctbk26847f6e57121708357";
    
    public Des3Encrypt() {
    	
	}
    
    public Des3Encrypt(String key){
    	this.key = key;
    }
    
    public String decrypt(String value) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), CRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            
            byte[] decodedByte = Base64.decodeBase64(value.getBytes());
            byte[] decryptedByte = cipher.doFinal(decodedByte);            
            return new String(decryptedByte);
        } catch(Exception e) {
        	log.error(e.getMessage(), e);
            return "";
        }
    }
    
    public String encrypt(String value) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), CRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            
            byte[] encryptedByte = cipher.doFinal(value.getBytes());
            byte[] encodedByte = Base64.encodeBase64(encryptedByte);
            return new String(encodedByte);
        } catch(Exception e) {
        	log.error(e.getMessage(), e);
            return "";
        }
    }
    
    public static void main(String[] args) {
		Des3Encrypt encrypt = new Des3Encrypt();
//		String decrypt = encrypt.decrypt("s/PM7op+ZniPuJ51MbP1eL2A0LfVupVl");
//		System.out.println(decrypt);
		System.out.println(encrypt.decrypt("s/PM7op+ZniPuJ51MbP1eL2A0LfVupVl"));
		System.out.println(encrypt.decrypt("H/hQzSmJZ84PDO3Bzgl4cL2A0LfVupVl"));
		System.out.println(encrypt.decrypt("6aWjCCNCMxnTFo6PHwzpjL2A0LfVupVl"));
		System.out.println(encrypt.decrypt("7AXj6SswT/aWQ1lHeS669L2A0LfVupVl"));
		System.out.println(encrypt.decrypt("uWkdaKZG/vakQbihDV19fL2A0LfVupVl"));
		System.out.println(encrypt.decrypt("aMS7XXuZeXsYIgmN+XiBjr2A0LfVupVl"));
		System.out.println(encrypt.decrypt("LoUCKgMgXDD8y2H/dDStV72A0LfVupVl"));
		System.out.println(encrypt.decrypt("U96UyXOzAUwm2kafK24Phr2A0LfVupVl"));
		System.out.println(encrypt.decrypt("t0tKHVkuZQu0ysxyvZG4Ab2A0LfVupVl"));
		System.out.println(encrypt.decrypt("1mbr6Vo30RyBBS/lX7XuFr2A0LfVupVl"));

//		System.out.println(encrypt.encrypt("张三 "));
	}
    
}
